<template>
  <div class="header-search" @click="enterSearchMode">
    <a-icon type="search" class="search-icon"/>
    <a-auto-complete
      ref="input"
      :getPopupContainer="getPopupContainer"
      :filter-option="filterOption"
      :class="['search-input', searchMode ? 'enter' : 'leave']"
      placeholder="站内搜索"
      @change="searchMethods"
      @blur="leaveSearchMode"
    >
      <template slot="dataSource">
        <a-select-option v-for="(site,index) in searchMenuOptions" :key="index" :value="site.fullPath">{{$t(getI18nKey(site.fullPath || site.path))}}</a-select-option>
      </template>
    </a-auto-complete>
  </div>
</template>

<script>
import { AutoComplete as AAutoComplete } from 'ant-design-vue'
import { mapGetters, mapState } from 'vuex'
import { getI18nKey } from '@/utils/routerUtil'
export default {
  components: { AAutoComplete },
  name: 'HeaderSearch',
  data() {
    return {
      searchMode: false,
      searchMenuOptions: []
    }
  },
  computed: {
    ...mapGetters('setting', ['menuData']),
    ...mapState('setting', ['fixedHeader'])
  },
  methods: {
    getI18nKey,
    enterSearchMode() {
      this.searchMode = true
      this.$emit('active', true)
      setTimeout(() => this.$refs.input.focus(), 300)
    },
    leaveSearchMode() {
      this.searchMode = false
      setTimeout(() => this.$emit('active', false), 300)
    },
    searchMethods(value) {
      const route = this.searchMenuOptions.filter(item => item.fullPath === value)[0]
      if (route.meta && route.meta.outside === 1) {
        window.open(route.meta.url, '_blank')
      } else {
        this.$router.push({ path: route.fullPath })
      }
      this.leaveSearchMode()
    },
    searchMenus(arr, menus) {
      for (const i of menus) {
        if (!i.meta.hidden && (!i.children || i.children.length === 0)) {
          arr.push(i)
        }
        if (i.children && i.children.length > 0) {
          this.searchMenus(arr, i.children)
        }
      }
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toUpperCase().indexOf(input.toUpperCase()) >= 0
      )
    },
    getPopupContainer(e) {
      return this.fixedHeader ? document.body : e.parentNode
    }
  },
  mounted() {
    const lists = []
    this.searchMenus(lists, this.menuData)
    this.searchMenuOptions = [...lists]
  }
}
</script>

<style lang="less">
  .header-search{
    .search-icon{
      font-size: 16px;
      cursor: pointer;
    }
    .search-input{
      border: 0;
      border-bottom: 1px solid @border-color-split;
      transition: width 0.3s ease-in-out;
      input{
        border: 0;
        box-shadow: 0 0 0 0;
      }
      &.leave{
        width: 0px;
        input{
          display: none;
        }
      }
      &.enter{
        width: 200px;
        input:focus{
          box-shadow: 0 0 0 0;
        }
      }
    }
  }
</style>
